package nacos

import (
	"log"

	"gitee.com/zawei/yggdrasil/pkg"
	"gitee.com/zawei/yggdrasil/pkg/config"
	"gitee.com/zawei/yggdrasil/pkg/config/source"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

type item struct {
	DataID string
	Group  string
	Format string
}

type nacosConfig struct {
	Client  *constant.ClientConfig
	Servers []constant.ServerConfig
	Items   []item
}

func init() {
	var err error
	cfg := &nacosConfig{}
	if err := config.Get("config.nacos").Scan(cfg); err != nil {
		log.Panic(err)
	}
	cfg.Client.AppName = pkg.AppName()
	if cfg.Client.CacheDir == "" {
		cfg.Client.CacheDir = "./conf/nacos"
	}
	if cfg.Client.LogDir == "" {
		cfg.Client.LogDir = "./log/nacos"
	}

	client, err := clients.NewConfigClient(vo.NacosClientParam{
		ClientConfig:  cfg.Client,
		ServerConfigs: cfg.Servers,
	})
	if err != nil {
		log.Fatal(err)
	}

	sources := make([]source.Source, 0, len(cfg.Items))
	for _, item := range cfg.Items {
		if item.Format == "" {
			item.Format = "json"
		}
		sources = append(sources, &nacosSource{item: &item, client: client})
	}
	if err := config.Load(sources...); err != nil {
		log.Fatal(err)
	}
}
